﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarolLib.Control;
using System.Xml;
using DispatchAssist.Service;
using System.Web.Services.Protocols;

namespace DispatchAssist.AppHost
{
    [ModuleContract("1DDE146C-934C-44A2-9D6E-C4D05CAB88F0", "系统管理", "用户管理")]
    public partial class UserManage : MdiUserControl
    {
        int rowID = -1;
        List<SeatUser> users = new List<SeatUser>();
        List<SeatUser> userlst = new List<SeatUser>();
        AuthService authService;

        public UserManage()
            : base()
        {
            InitializeComponent();
        }

        public UserManage(XmlNode node)
            : this()
        {
        }

       

        public override void Onload()
        {
            base.Onload();
            authService = new AuthService();
            authService.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();
            BindUserList(0);

            grpEditUser.Width = this.Width;
        }

        public override void Unload()
        {
            base.Unload();

            users = null;
            userlst = null;

            authService = null;
        }

        private void btnCreateEdit_Click(object sender, EventArgs e)
        {
            if ((sender as Button).Tag.ToString() == "create")
            {
                CreateUser();
            }
            else if ((sender as Button).Tag.ToString() == "edit")
            {
                EditUser();
            }
        }

        private void EditUser()
        {
            if (this.dgrdUserList.SelectedRows == null || dgrdUserList.SelectedRows.Count <= 0 || dgrdUserList.SelectedRows.Count > 1)
            {
                MessageBox.Show("请选择要编辑的记录行！");
                return;
            }
            try
            {
                rowID = this.dgrdUserList.SelectedRows[0].Index;
            }
            catch
            {
                rowID = 0;
            }
            BindRole();
            Guid userID = new Guid(System.Convert.ToString(dgrdUserList.SelectedRows[0].Cells["UserID"].Value));
            Guid roleID = new Guid(System.Convert.ToString(dgrdUserList.SelectedRows[0].Cells["RoleID"].Value));
            cmbRole.SelectedValue = roleID;
            string userName = System.Convert.ToString(dgrdUserList.SelectedRows[0].Cells["UserName"].Value);
            this.btnSave.Tag = userID;
            grpEditUser.Visible = true;
            this.chkChangePassword.Visible = true;
            this.chkChangePassword.Checked = false;
            this.pnlPassword.Visible = false;
            txtConfirmPassword.Text = string.Empty;
            this.txtPassword.Text = string.Empty;
            this.txtUserName.Text = userName;
            this.btnCreate.Enabled = false;
            this.btnEdit.Enabled = false;
            this.btnDelete.Enabled = false;


        }

        private void CreateUser()
        {
            BindRole();
            //to do 
            try
            {
                rowID = this.dgrdUserList.SelectedRows[0].Index;
            }
            catch
            {
                rowID = 0;
            }
            grpEditUser.Visible = true;
            cmbRole.SelectedIndex = 0;
            this.chkChangePassword.Visible = false;
            this.pnlPassword.Visible = true;
            txtConfirmPassword.Text = string.Empty;
            this.txtPassword.Text = string.Empty;
            this.txtUserName.Text = string.Empty;
            this.btnSave.Tag = "create";
            this.btnCreate.Enabled = false;
            this.btnEdit.Enabled = false;
            this.btnDelete.Enabled = false;
        }

        private void BindRole()
        {
            try
            {
                List<SeatRole> allRoles = authService.GetAllSeatRole().ToList<SeatRole>();

                //add at 2011-8-22 by wuzhongqi /for bug 0000989

                List<SeatRole> enableRoles = GetEnableRoles(allRoles, AuthContext.Current.Role.PowerFlag);
                enableRoles.Insert(0, new SeatRole() { RoleID = new Guid(), RoleName = "请选择用户角色" });
                cmbRole.DataSource = enableRoles;
                cmbRole.DisplayMember = "RoleName";
                cmbRole.ValueMember = "RoleID";
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        /// <summary>
        /// 获取当前权限可以分配的角色列表
        /// </summary>
        /// <returns></returns>
        private List<SeatRole> GetEnableRoles(List<SeatRole> allRoles,int currentRoles)
        {
           return allRoles.Where(f => (currentRoles | f.PowerFlag) == currentRoles).ToList();
        }

        private void BindUserList(int flag)
        {
            SeatUser[] arrUser = authService.GetAllSeatUser(flag);
            if (arrUser != null)
            {
                users = arrUser.Where(f => (AuthContext.Current.Role.PowerFlag | f.PowerFlag) == AuthContext.Current.Role.PowerFlag).ToList<SeatUser>();//.ToList<SeatUser>();

                dgrdUserList.AutoGenerateColumns = false;
                dgrdUserList.DataSource = users;

                dgrdUserList.Rows[0].Selected = true;
               
            }
            this.btnDelete.Enabled = true;
            this.btnCreate.Enabled = true;
            this.btnEdit.Enabled = true;
            grpEditUser.Visible = false;

            dgrdUserList.Columns["UserID"].Visible = false;

            dgrdUserList.Width = this.Width - 70;

            dgrdUserList.Update();
        }

        private string GetStatusName(int status)
        {
            string str = "";
            switch (status)
            {
                case 0:
                    str = "启用";
                    break;
                case 1:
                    str = "禁用";
                    break;
                default:
                    break;
            }
            return str;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string tag = System.Convert.ToString((sender as Button).Tag);
            userlst = authService.GetAllSeatUser(0).ToList<SeatUser>();
            SeatUser user = null;
            if (userlst != null && userlst.Count > 0)
            {
                user = userlst.Find(s => s.UserName == txtUserName.Text);

            }
            if (tag == "create")
            {
                if (!IsValidUser())
                {
                    return;
                }
                else
                {
                    if (user != null)
                    {
                        MessageBox.Show("该用户已经存在！");
                        return;
                    }

                    SaveNewUser();
                }
            }
            else if (!string.IsNullOrEmpty(tag))
            {
                if (!IsValidUser())
                {
                    return;
                }
                else
                {
                    SeatUser userr = userlst.Find(s => s.UserID == new Guid(tag));

                    if (userr.UserName != txtUserName.Text && user != null)
                    {
                        MessageBox.Show("该用户已经存在！");
                        return;
                    }
                    SaveUser(tag);
                }
            }
        }

        private void SaveUser(string userID)
        {
            SeatUser user = new SeatUser();
            user.UserID = new Guid(userID);
            user.UserName = txtUserName.Text;
            user.RoleID = new Guid(System.Convert.ToString(((SeatRole)(cmbRole.SelectedItem)).RoleID));
            try
            {
                if (chkChangePassword.Checked == true)
                {
                    user.Password = CarolLib.EncryptHelper.GetPassword(txtPassword.Text);
                }
                if (authService.UpdateSeatUser(user))
                {
                    BindUserList(0);
                    MessageBox.Show("保存成功！");
                    this.btnCreate.Enabled = true;
                    this.btnEdit.Enabled = true;
                    this.btnDelete.Enabled = true;
                }
                else
                {
                    MessageBox.Show("保存失败,请检查输入或与管理员联系！");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void SaveNewUser()
        {
            SeatUser user = new SeatUser();
            user.UserName = txtUserName.Text;
            user.RoleID = new Guid(System.Convert.ToString(((SeatRole)(cmbRole.SelectedItem)).RoleID));
            user.Password = CarolLib.EncryptHelper.GetPassword(txtPassword.Text);
            try
            {
                if (authService.CreateSeatUser(user))
                {
                    BindUserList(0); 
                    MessageBox.Show("添加成功！");
                    this.btnCreate.Enabled = true;
                    this.btnEdit.Enabled = true;
                    this.btnDelete.Enabled = true;
                }
                else
                {
                    MessageBox.Show("添加失败,请检查输入或与管理员联系！");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private bool IsValidUser()
        {
            if (string.IsNullOrEmpty(txtUserName.Text))
            {
                MessageBox.Show("请输入用户名称！");
                return false;
            }

            if (((SeatRole)(cmbRole.SelectedItem)).RoleName == "请选择用户角色")
            {
                MessageBox.Show("请选择用户角色！");
                return false;
            }
            if (this.chkChangePassword.Visible == false || chkChangePassword.Checked == true)
            {
                if (string.IsNullOrEmpty(this.txtPassword.Text))
                {
                    MessageBox.Show("请输入用户密码！");
                    return false;
                }
                if (string.IsNullOrEmpty(this.txtConfirmPassword.Text))
                {
                    MessageBox.Show("请输入确认密码！");
                    return false;
                }
                if (this.txtConfirmPassword.Text != txtPassword.Text)
                {
                    MessageBox.Show("两次密码输入不一致！");
                    return false;


                }

            }
            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
           // this.pnlUserList.Visible = true;
            this.grpEditUser.Visible = false;
            this.btnCreate.Enabled = true;
            this.btnEdit.Enabled = true;
            this.btnDelete.Enabled = true;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.dgrdUserList.SelectedRows == null || dgrdUserList.SelectedRows.Count <= 0 || dgrdUserList.SelectedRows.Count > 1)
            {
                MessageBox.Show("请选择要编辑的记录行！");
                return;
            }
            Guid userID = new Guid(System.Convert.ToString(dgrdUserList.SelectedRows[0].Cells["UserID"].Value));
            try
            {
                SeatUser su = users.Find(s => s.UserID == userID);

                if (authService.DeleteSeatUser(userID, (!su.DeleteFlag)))
                {
                   // BindUserList(0);
                    
                    if (su.DeleteFlag)
                    {
                        MessageBox.Show("启用成功！");
                        dgrdUserList.SelectedRows[0].Cells["UserStatus"].Value = "启用";
                    }
                    else
                    {
                        MessageBox.Show("禁用成功！");
                        dgrdUserList.SelectedRows[0].Cells["UserStatus"].Value = "禁用";
                    }
                    su.DeleteFlag = !su.DeleteFlag;

                    btnDelete.Text = su.DeleteFlag? "启用" : "禁用";
                }
                else
                {
                    MessageBox.Show("操作失败！");
                }
            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }

        private void chkChangePassword_CheckedChanged(object sender, EventArgs e)
        {
            this.pnlPassword.Visible = this.chkChangePassword.Checked;
        }

        private void dgrdUserList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((rowID != -1) && grpEditUser.Visible && (dgrdUserList.SelectedRows[0].Index != rowID))
            {
                if (MessageBox.Show("是否撤销当前编辑？", "编辑确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    dgrdUserList.Rows[rowID].Selected = true;
                }
                else
                {
                    grpEditUser.Visible = false;
                    this.btnCreate.Enabled = true;
                    this.btnEdit.Enabled = true;
                    this.btnDelete.Enabled = true;
                }
            }
        }

        private void dgrdUserList_SelectionChanged(object sender, EventArgs e)
        {
            if (dgrdUserList.Rows.Count == 0) return;

            int index = 0;
            try
            {
                index = dgrdUserList.SelectedRows[0].Index;
            }
            catch
            {
                return;
            }
            SeatUser seatUser = new SeatUser();

            if (dgrdUserList.Rows[index].Cells[0].Value == null)
            {
                if (users.Count > 0)
                {
                    if (index > users.Count - 1)
                    {
                        seatUser = new SeatUser();
                    }
                    else
                    {
                        seatUser = users[0];
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {

                Guid selectedID = (Guid)dgrdUserList.Rows[index].Cells[0].Value;
                dgrdUserList.Rows[index].Selected = true;
                //setBtnEnabled(true);


                seatUser = users.Find(s => s.UserID == selectedID);
                if (seatUser == null) seatUser = new SeatUser();

                btnDelete.Text = (seatUser.DeleteFlag == true) ? "启用" : "禁用";

            }

        }

      
    }
}
